using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 阳光生产攻击策略 - 用于向日葵等植物生产阳光
/// </summary>
public class ProduceStrategy : AttackStrategyBase
{
    private Coroutine m_ProductionCoroutine;

    public ProduceStrategy(SkillData data)
    {
        AttackData = data;
    }

    public override void Execute(Entity entity)
    {
        if (m_ProductionCoroutine == null)
        {
            m_ProductionCoroutine = Owner.StartCoroutine(SunProductionRoutine());
        }
    }

    private IEnumerator SunProductionRoutine()
    {
        while (Owner.HealthComponent.CurHealth > 0)
        {
            yield return new WaitForSeconds(AttackData.Interval);

            if (Owner == null) yield break;

            GenerateSun();
        }
    }

    /// <summary>
    /// 生成阳光 - 根据技能数据类型决定生成数量
    /// </summary>
    private void GenerateSun()
    {
        // 统一使用 Damage 字段作为阳光价值
        int sunAmount = (int)AttackData.Damage;
        int sunCount = 1; // 默认生成数量
        
        // 检查是否是双生向日葵技能数据
        if (AttackData is TwinSunFlowerSkillData twinSunData)
        {
            // 双生向日葵：使用 SunAmountMultiplier 作为生成数量
            sunCount = twinSunData.SunAmountMultiplier;
        }
        
        // 根据计算出的数量生成阳光
        for (int i = 0; i < sunCount; i++)
        {
            GenerateSingleSun(sunAmount);
        }
    }

    /// <summary>
    /// 生成单个阳光
    /// </summary>
    /// <param name="sunValue">阳光价值</param>
    private void GenerateSingleSun(int sunValue)
    {
        // 从对象池获取阳光实例
        GameObject sunObj = SunPool.Instance.GetSun();
        if (sunObj == null)
        {
            Logger.LogWarning("ProduceStrategy", "无法从SunPool获取阳光对象");
            return;
        }

        sunObj.transform.SetParent(Owner.transform);

        // 计算向日葵周围的随机生成位置
        Vector3 randomOffset = Random.insideUnitCircle * AttackData.IndicatorData.Range;
        Vector3 spawnPosition = sunObj.transform.position + new Vector3(randomOffset.x, 2f, randomOffset.y);

        sunObj.transform.localPosition = Vector3.zero;
        sunObj.SetActive(true);

        // 设置阳光价值
        Sun sun = sunObj.GetComponent<Sun>();
        if (sun != null)
        {
            sun.Initialize(sunValue);
            sun.DoJump(Owner.transform);
        }
        else
        {
            Logger.LogWarning("ProduceStrategy", "阳光对象缺少Sun组件");
        }
    }

    public override void Cancel()
    {
        if (m_ProductionCoroutine != null)
        {
            Owner.StopCoroutine(m_ProductionCoroutine);
            m_ProductionCoroutine = null;
        }
    }
}
